//
//  XTEncrypt+AES.m
//  XTEncryptKit
//
//  Created by Tong on 2017/6/11.
//  Copyright © 2017年 Tong. All rights reserved.
//

#import "XTEncrypt+AES.h"

#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCrypto.h>

@implementation XTEncrypt (AES)

#pragma mark - NSString

/**
 获取 AES256 加密的 NSString
 
 @param sourceString 需要加密的 NSString
 @param key 加密 Key
 @return 加密后的 NSString
 */
+ (NSString *)getAes256EncryptStringFromString:(NSString *)sourceString byEncryptKey:(NSString *)key
{
    const char *cstr = [sourceString cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:sourceString.length];

    /** 对数据进行加密 */
    NSData *result = [self getAes256EncryptDataFromData:data byEncryptKey:key];
    
    /** 转换为二进制字符串 */
    if (result && result.length > 0) {
        
        Byte *datas = (Byte*)[result bytes];
        NSMutableString *output = [NSMutableString stringWithCapacity:result.length * 2];
        
        for(int i = 0; i < result.length; i++){
            [output appendFormat:@"%02x", datas[i]];
        }
        return output;
    }
    
    return nil;
}


/**
 获取 AES256 解密后 NSString
 
 @param sourceString 需要解密的 NSString
 @param key 加密 Key
 @return 解密后的 NSString
 */
+ (NSString *)getAes256DecryptFromString:(NSString *)sourceString byEncryptKey:(NSString *)key
{
    /** 转换为二进制数据 */
    NSMutableData *data = [NSMutableData dataWithCapacity:sourceString.length / 2];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
   
    for (int i = 0; i < [sourceString length] / 2; i++) {
        
        byte_chars[0] = [sourceString characterAtIndex:i * 2];
        byte_chars[1] = [sourceString characterAtIndex:i * 2 + 1];
        whole_byte = strtol(byte_chars, NULL, 16);
        [data appendBytes:&whole_byte length:1];
    }
    
    /** 对数据进行解密 */
    NSData* result = [self getAes256DecryptDataFromData:data byEncryptKey:key];
    if (result && result.length > 0) {
        return [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
    }
    
    return nil;
}


#pragma mark - NSData

/**
 获取 AES256 加密的 NSData
 
 @param sourceData 需要加密的NSData
 @param key 加密 Key
 @return 加密后的 NSData
 */
+ (NSData *)getAes256EncryptDataFromData:(NSData *)sourceData byEncryptKey:(NSString *)key
{
    char keyPtr[kCCKeySizeAES256 + 1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
  
    NSUInteger dataLength = [sourceData length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    
    size_t numBytesEncrypted = 0;
    
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          keyPtr, kCCBlockSizeAES128,
                                          NULL,
                                          [sourceData bytes], dataLength,
                                          buffer, bufferSize,
                                          &numBytesEncrypted);
    
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }
    free(buffer);
    return nil;
}


/**
 获取 AES256 解密的 NSData
 
 @param sourceData 需要解密的 NSData
 @param key 加密 Key
 @return 解密后的 NSData
 */
+ (NSData *)getAes256DecryptDataFromData:(NSData *)sourceData byEncryptKey:(NSString *)key
{
    char keyPtr[kCCKeySizeAES256+1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
   
    NSUInteger dataLength = [sourceData length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    
    size_t numBytesDecrypted = 0;
    
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          keyPtr, kCCBlockSizeAES128,
                                          NULL,
                                          [sourceData bytes], dataLength,
                                          buffer, bufferSize,
                                          &numBytesDecrypted);
    
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
    }
    free(buffer);
    return nil;
}


@end











